package com.spring.sunflower.userinfo;

import android.content.Intent;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.LabelBean;
import com.spring.sunflower.bean.STSCertBean;
import com.spring.sunflower.bean.UserInfoUpdateBean;
import com.spring.sunflower.common.CommonContract;
import com.spring.sunflower.common.FileUploadCallback;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.dialog.NoticeDialog;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.util.AliUploadUtils;
import com.spring.sunflower.util.AudioUtils;
import com.spring.sunflower.widget.ProgressView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Kevin on 2021/7/3<br/>
 * <p>
 * Describe:<br/>
 */
public class VoiceSignActivity extends BaseActivity<VoiceSignPresenter> implements CommonContract.VoiceSignView, View.OnClickListener {
    private TextView tvContent, tvVoicePlay, tvChange, tvVoiceRerecord, tvVoiceSubmit, tvVoiceTip;
    private ImageView ivVoiceRerecord, ivVoicePlay, ivVoiceSubmit;
    List<LabelBean.DatasBean> mData = new ArrayList<>();
    private boolean isRecording = false;//录音中
    private boolean isRecordFinish = false;//录音结束
    private boolean isRecordPlay = false;//试听过程
    private boolean isRecordPlayFinish = false;//试听结束
    private AudioUtils audioUtils;
    private Timer mRecorderTimer;
    private int mRecorderTime;
    private String audioLocalPath;
    private String keyID;
    private String keySecret;
    private String securityToken;
    private String audioNetPath;
    private AliUploadUtils aliUploadUtils;
    private ProgressView progressView;

    @Override
    public void initView() {
        Intent intent = getIntent();
//        keyID = intent.getStringExtra(Constant.ALI_KEY_ID);
//        keySecret = intent.getStringExtra(Constant.ALI_KEY_SECRET);
//        securityToken = intent.getStringExtra(Constant.ALI_SECURITY_TOKEN);
//        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
        tvTitle.setText("语音签名");
        tvChange = findViewById(R.id.tvChange);
        tvContent = findViewById(R.id.tvContent);
        tvVoicePlay = findViewById(R.id.tv_voice_play);
        tvVoiceRerecord = findViewById(R.id.tv_voice_rerecord);
        tvVoiceSubmit = findViewById(R.id.tv_voice_submit);
        tvVoiceTip = findViewById(R.id.tvVoiceTip);
        progressView = findViewById(R.id.pvProgress);
        progressView.setVisibility(View.GONE);

        ivVoiceRerecord = findViewById(R.id.iv_voice_rerecord);
        ivVoicePlay = findViewById(R.id.iv_voice_record);
        ivVoiceSubmit = findViewById(R.id.iv_voice_submit);
        tvVoicePlay.setText("点击录制");
        ivVoicePlay.setImageResource(R.drawable.ic_voice_record);
        tvVoicePlay.setText("点击录制");

        hideOtherButton();

        tvChange.setOnClickListener(this);
        ivVoicePlay.setOnClickListener(this);
        ivVoiceRerecord.setOnClickListener(this::onClick);
        ivVoiceSubmit.setOnClickListener(this::onClick);
        audioUtils = AudioUtils.getInstance();
        mPresenter.getTextTemplate();
        mPresenter.getSTSCert();
    }

    private void hideOtherButton() {
        ivVoiceRerecord.setVisibility(View.INVISIBLE);
        ivVoiceSubmit.setVisibility(View.INVISIBLE);
        tvVoiceRerecord.setVisibility(View.INVISIBLE);
        tvVoiceSubmit.setVisibility(View.INVISIBLE);
    }

    private void showOtherButton() {
        ivVoiceRerecord.setVisibility(View.VISIBLE);
        ivVoiceSubmit.setVisibility(View.VISIBLE);
        tvVoiceRerecord.setVisibility(View.VISIBLE);
        tvVoiceSubmit.setVisibility(View.VISIBLE);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_voice_sign;
    }

    @Override
    public VoiceSignPresenter setPresenter() {
        return new VoiceSignPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvChange:
                if (mData.size() > 0) {
                    int i = new Random().nextInt(mData.size());
                    tvContent.setText(mData.get(i).getName());
                }
                break;
            case R.id.iv_voice_record:
                if (!isRecording && !isRecordFinish && !isRecordPlay && !isRecordPlayFinish) {
                    if (XXPermissions.isGranted(VoiceSignActivity.this, Permission.RECORD_AUDIO)) {
                        //开始录音
                        startRecord();
                    } else {
                        showPermissionIntroDialog(getString(R.string.permission_audio_title),
                                getString(R.string.permission_audio_desc), new OnPermissionIntroClickListener() {
                                    @Override
                                    public void onClickOK() {
                                        XXPermissions.with(VoiceSignActivity.this)
                                                .permission(Permission.RECORD_AUDIO)
                                                .request(new OnPermissionCallback() {
                                                    @Override
                                                    public void onGranted(List<String> permissions, boolean all) {
                                                        startRecord();
                                                    }

                                                    @Override
                                                    public void onDenied(List<String> permissions, boolean never) {
                                                        showPermissionIntroDialog(
                                                                getString(R.string.permission_denied_title),
                                                                "无法进行录音",
                                                                null
                                                        );
                                                    }
                                                });
                                    }

                                    @Override
                                    public void onClickCancel() {
                                        showPermissionIntroDialog(
                                                getString(R.string.permission_denied_title),
                                                "无法进行录音",
                                                null
                                        );
                                    }
                                });
                    }
                } else if (isRecording) {
                    stopRecorder();
                } else if (isRecordFinish && !isRecordPlay) {
                    startPlay();
                } else if (isRecordPlay) {
                    stopPlay();
                }

                break;
            case R.id.iv_voice_rerecord:
                isRecordPlayFinish = false;
                startRecord();
                break;
            case R.id.iv_voice_submit:
                if (isFastClick()) return;
                NoticeDialog dialog = showNoticeDialog("温馨提示", "确定提交审核吗", "提交后将退出该页面，并等待审核", "确定", new OnPermissionIntroClickListener() {
                    @Override
                    public void onClickCancel() {

                    }

                    @Override
                    public void onClickOK() {
                        showLoading();
                        aliUploadUtils.upLoadFile(audioLocalPath, new FileUploadCallback() {
                            @Override
                            public void onFailure(String str) {
                                hideLoading();
                                showToast(str);
                            }

                            @Override
                            public void onSuccess(Object paramRequestString, String filePath) {
                                Map<String, String> map = new HashMap<>();
                                map.put("voiceSignatureDuration", mRecorderTime + "");
                                map.put("voiceSignature", filePath);
                                mPresenter.updateUserInfo(map);
                            }

                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                            }
                        });
                    }
                });
                break;
        }
    }

    private void startRecord() {
        Constant.shouldShowCallDialog = false;
        Constant.shouldShowLuckyMatchDialog = false;
        isRecording = true;
        tvVoicePlay.setText("录制中...");
        ivVoicePlay.setImageResource(R.drawable.ic_voice_recording);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getCacheDir().getAbsolutePath());
        stringBuilder.append("/");
        stringBuilder.append(System.currentTimeMillis());
        stringBuilder.append(".amr");
        audioLocalPath = stringBuilder.toString();
        audioUtils.starRecord(audioLocalPath);
        startTimer();
        hideOtherButton();
    }

    @Override
    public void showTextTemplate(List<LabelBean.DatasBean> data) {
        mData = data;
        if (data.size() > 0) {
            int i = new Random().nextInt(data.size());
            tvContent.setText(data.get(i).getName());
        }
    }

    @Override
    public void updateSuccess(UserInfoUpdateBean.DatasBean bean) {
        hideLoading();
        showToast("提交成功");
        Intent intent = new Intent(this, VoiceSignActivity.class);
        intent.putExtra(Constant.USER_VOICE_SIGN, bean);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void updateFailed() {
        hideLoading();
    }

    @Override
    public void loadSTSCert(STSCertBean.DatasBean data) {
        keyID = data.getAccessKeyId();
        keySecret = data.getAccessKeySecret();
        securityToken = data.getSecurityToken();
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
    }

    private void startTimer() {
        progressView.setVisibility(View.VISIBLE);
        mRecorderTime = 0;
        mRecorderTimer = new Timer();
        mRecorderTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvVoiceTip.setText(++mRecorderTime + "''");
                        progressView.setProgress(mRecorderTime * 100 / 60.0f);
                        if (mRecorderTime >= 60) {
                            stopRecorder();
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    private void stopRecorder() {
        isRecordFinish = true;
        isRecording = false;
        audioUtils.cancelRecord();
        tvVoicePlay.setText("试听");
        ivVoicePlay.setImageResource(R.drawable.ic_voice_play);
        showOtherButton();
        tvVoiceTip.setVisibility(View.INVISIBLE);
        cancelTimer();
        progressView.setVisibility(View.GONE);
    }

    private void cancelTimer() {
        if (mRecorderTimer != null) {
            mRecorderTimer.cancel();
            mRecorderTimer = null;
        }
    }

    private void startPlay() {
        isRecordPlay = true;
        isRecording = false;
        tvVoicePlay.setText("暂停");
        ivVoicePlay.setImageResource(R.drawable.ic_voice_pause);
        hideOtherButton();
        audioUtils.play(audioLocalPath, new AudioUtils.PlayCallBack() {
            @Override
            public void onCompletion(MediaPlayer param1MediaPlayer) {
                tvVoicePlay.setText("试听");
                isRecordPlay = false;
                isRecordPlayFinish = true;
                ivVoicePlay.setImageResource(R.drawable.ic_voice_play);
                showOtherButton();
            }

            @Override
            public void onPrepared(MediaPlayer param1MediaPlayer) {

            }
        });
    }

    private void stopPlay() {
        isRecordPlay = false;
        tvVoicePlay.setText("试听");
        ivVoicePlay.setImageResource(R.drawable.ic_voice_play);
        audioUtils.stopPlay();
        isRecordPlayFinish = true;
        showOtherButton();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Constant.shouldShowCallDialog = true;
        Constant.shouldShowLuckyMatchDialog = true;
    }
}
